package com.sky.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

@Component
@ServerEndpoint("/ws/{sid}")
@Slf4j
public class WebsocketService {
    //存放会话对象
    private static final Map<String, Session> sessionMap = new HashMap<>();

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void OnOpen(Session session, @PathParam("sid") String sid){
        log.info("客户端：{} 连接成功", sid);
        sessionMap.put(sid,session);
    }

    /**
     * 收到客户端消息后调用的方法
     */
    @OnMessage
    public void OnMessage(String message, @PathParam("sid") String sid){
        log.info("接收到客户端：{} 的消息：{}", sid, message);
    }

    @OnClose
    public void OnClose(@PathParam("sid") String sid){
        log.info("客户端：{} 已关闭连接", sid);
        sessionMap.remove(sid);
    }

    /**
     * 给所有客户端发送消息
     */
    public void sendAllClient(String message){
        Collection<Session> sessions = sessionMap.values();
        sessions.forEach(session -> {
            try {
                session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
    }
}
